package com.shejiao.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Component
public class FileUtil {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FileUtil.class);

    //静态变量处理,@Component,@Autowired,@PostConstruct三步
    @Autowired
    private AliOssConfig autoAliOssConfig;
    private static AliOssConfig aliOssConfig;
    @PostConstruct
    public void init() {
        aliOssConfig = autoAliOssConfig;
    }

    public static String upload(FileFormat fileFormat){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOssConfig.getEndpoint(),
                aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret());

        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        String objectName = fileFormat.getName();
        ossClient.putObject(aliOssConfig.getBucket(), objectName, new ByteArrayInputStream(fileFormat.getContent()));

        // 关闭OSSClient。
        ossClient.shutdown();

        return fileFormat.getName();
    }


    public static InputStream dowanload(String objectName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOssConfig.getEndpoint(),
                aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret());

        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(aliOssConfig.getBucket(), objectName);
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();

        // 关闭OSSClient。
        //ossClient.shutdown();

        return content;



//        InputStream is=FileUtil.dowanload("1.jpg");
//        FileOutputStream os=new FileOutputStream("/Users/lxs/Downloads/1.jpg");
//        byte[] buffer = new byte[1024];
//        while (is.read(buffer)!=-1){
//            os.write(buffer);
//        }
//        os.flush();
//        os.close();
//        is.close();
    }

}
